package main.java.com.itlin.datastructure.stack;

import java.util.Iterator;

public class ArrayStack<E> implements Stack<E>, Iterable<E>{

    //用数组实现
    private E[] array;
    private int top;//栈顶指针

    /*
     * 底                顶
     * 0    1   2   3   4
     */

    @SuppressWarnings("all")
    public ArrayStack(int capacity){
        this.array = (E[]) new Object[capacity];
    }
    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            int index = top ;
            @Override
            public boolean hasNext() {
                return index > 0;
            }

            @Override
            public E next() {
                return array[--index];
            }
        };
    }

    @Override
    public boolean push(E value) {
        if(isFull()){
            return false;
        }
        array[top++] = value;
        return true;
    }

    @Override
    public E pop() {
        if(isEmpty()){
            return null;
        }
        E e = array[--top];
        array[top] = null;
        return e;
    }

    @Override
    public E peek() {
        if (isEmpty()){
            return null;
        }

        return array[top-1];

    }

    @Override
    public boolean isEmpty() {
        return top == 0;
    }

    @Override
    public boolean isFull() {
        return top == array.length;
    }
}
